package com.geoai.uimap.core.osmdroid

import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapArc
import com.geoai.uimap.geo.Point
import com.geoai.uimap.geo.SimpleProjection
import com.geoai.uimap.utils.MathUtils
import com.geoai.uimap.utils.SphericalUtil
import com.geoai.uimap.utils.getOsmMapView
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.overlay.Polyline

class OsmMapArc(private val map: IGEOMap) : GEOMapArc() {
    private var mPolyline: Polyline? = null
    override fun show(): GEOMapArc {
        if (mArcInfo == null) return this
        val mapView = map.getOsmMapView() ?: return this
        val startPoint = mArcInfo!!.start
        val endPoint = mArcInfo!!.end
        val simpleProjection = SimpleProjection(startPoint) //基点
        val s = simpleProjection.GeoPoint2Point(startPoint)
        val e = simpleProjection.GeoPoint2Point(endPoint)
        val mRadius = SphericalUtil.computeDistanceBetween(startPoint, endPoint) / 2

        val circleOnAftTurn: MathUtils.Circle = MathUtils.Circle()
        circleOnAftTurn.center.x = (s.x + e.x) / 2
        circleOnAftTurn.center.y = (s.y + e.y) / 2
        circleOnAftTurn.radius = mRadius
        val points = mutableListOf<GeoPoint>()
        var subAngle = 0.0
        while (Math.abs(subAngle) <= Math.abs(mArcInfo!!.mAngel)) {
            val mid = Point()
            val angleCos = Math.cos(Math.toRadians(subAngle))
            val angleSin = Math.sin(Math.toRadians(subAngle))
            mid.x =
                    (circleOnAftTurn.center.x + (s.x - circleOnAftTurn.center.x) * angleCos - (s.y - circleOnAftTurn.center.y) * angleSin)
            mid.y =
                    (circleOnAftTurn.center.y + (s.x - circleOnAftTurn.center.x) * angleSin + (s.y - circleOnAftTurn.center.y) * angleCos)
            val midPoint = simpleProjection.Point2GeoPoint(mid)
            points.add(GeoPoint(midPoint.latitude, midPoint.longitude))
            if (mArcInfo!!.mClockwise) {
                subAngle -= 2.0
            } else {
                subAngle += 2.0
            }
        }
        mPolyline = Polyline(mapView)
        mPolyline?.let {
            it.setPoints(points)
            it.outlinePaint.color = mLineColor
            it.outlinePaint.strokeWidth = mWidth
        }
        mapView.overlayManager.add(mPolyline)
        mapView.invalidate()


        return this
    }


    override fun destroy() {
        map.getOsmMapView()?.let {
            it.overlayManager.remove(mPolyline)
            it.invalidate()
        }
    }
}